<?php

namespace App\Http\Controllers;

use App\Events\Out\EventGiftLessonAccepted;
use App\Exceptions\GiftLessonAcceptanceExistException;
use App\Exceptions\GiftLessonShareAcceptedException;
use App\Exceptions\GiftLessonShareExpiredException;
use App\Exceptions\GiftLessonShareInvalidAcceptanceException;
use App\Facades\KafkaBridge;
use App\Http\Response\CreatedResponse;
use App\Models\GiftLessonAcceptance;
use App\Models\GiftLessonShare;
use App\Models\GiftLessonStudent;
use App\Models\StudentFirstBillingTime;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;

class GiftLessonAcceptanceController extends BaseController
{
    //

    public function accept(Request $request)
    {
        $this->validate($request, [
            'code' => 'required|string',
        ]);

        $studentId = intval($request->header("X-Authenticated-Userid"));
        $share = GiftLessonShare::where('share_code', $request->input('code'))->first();
        if (empty($share)) {
            throw new GiftLessonShareAcceptedException();
        }

        $acceptance = $share->acceptances()->first();
        if (!empty($acceptance) && $acceptance->getStudentId() == $studentId) {
            return new CreatedResponse();
        }

        if ($share->getStatus() !== GiftLessonShare::STATUS_CREATED) {
            throw new GiftLessonShareAcceptedException();
        }
        if (Carbon::now()->greaterThan($share->getExpiredAt())) {
            throw new GiftLessonShareExpiredException();
        }

        $acceptedCount = GiftLessonAcceptance::where('student_id', $studentId)->count();
        if ($acceptedCount) {
            throw new GiftLessonAcceptanceExistException();
        }

        $firstBilling = StudentFirstBillingTime::find($studentId);
        if (!empty($firstBilling) && $firstBilling->getBillId()) {
            throw new GiftLessonShareInvalidAcceptanceException();
        }

        $share->setStatus(GiftLessonShare::STATUS_ACCEPTED);
        $share->save();

        $acceptance = new GiftLessonAcceptance();
        $acceptance->setStudentId($studentId);
        $acceptance->setShareId($share->getId());
        $acceptance->setLessonCount(GiftLessonStudent::ACCEPT_LESSON_COUNT);
        $acceptance->setExpiredAt(Carbon::now()->addDays(GiftLessonAcceptance::EXPIRE_DAYS));
        $acceptance->setStatus(GiftLessonAcceptance::STATUS_ACCEPTED);
        $acceptance->save();

        $event = new EventGiftLessonAccepted();
        $event->studentId = $studentId;
        $event->shareId = $share->getId();
        $event->lessonCount = GiftLessonStudent::ACCEPT_LESSON_COUNT;

        KafkaBridge::push($event);

        return new CreatedResponse();

    }
}
